package com.csun.dsms.service.impl;

import com.csun.dsms.comment.base.enums.ErrorCodeEnum;
import com.csun.dsms.comment.base.exception.BusinessException;
import com.csun.dsms.comment.core.support.BaseService;
import com.csun.dsms.comment.core.support.CsunMessageSource;
import com.csun.dsms.mapper.DsmsPoorMapper;
import com.csun.dsms.model.domain.*;
import com.csun.dsms.model.dto.poor.ApplyPoorDto;
import com.csun.dsms.model.dto.poor.PoorDto;
import com.csun.dsms.model.dto.poor.PoorQueryDto;
import com.csun.dsms.model.dto.record.RecordPercentDto;
import com.csun.dsms.model.enums.PoorStatusEnum;
import com.csun.dsms.model.vo.poor.PoorNumberVo;
import com.csun.dsms.model.vo.poor.PoorProjectVo;
import com.csun.dsms.model.vo.poor.PoorVo;
import com.csun.dsms.model.vo.record.ProjectPercentVo;
import com.csun.dsms.model.vo.record.RecordPercentVo;
import com.csun.dsms.service.DsmsPoorProjectService;
import com.csun.dsms.service.DsmsPoorService;
import com.csun.dsms.service.DsmsRecordService;
import com.csun.dsms.service.DsmsUnitService;
import com.csun.dsms.utils.DateUtil;
import com.csun.dsms.utils.IDCardUtil;
import com.csun.dsms.utils.PublicUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author chisj chisj@foxmail.com
 * @version 1.0.0
 * @date 2021-09-16 16:31
 * @description: TODO
 */
@Slf4j
@Service
@Transactional
public class DsmsPoorServiceImpl extends BaseService<DsmsPoor> implements DsmsPoorService {

    @Resource
    private DsmsPoorMapper dsmsPoorMapper;
    @Resource
    private DsmsUnitService dsmsUnitService;
    @Resource
    private DsmsPoorProjectService dsmsPoorProjectService;
    @Resource
    private DsmsRecordService dsmsRecordService;
    @Resource
    private CsunMessageSource csunMessageSource;

    /**
     * 查询特困人员列表
     *
     * @param poorQueryDto the poor query dto
     * @return the poor vo list.
     */
    @Override
    public List<PoorVo> queryListWithPage(PoorQueryDto poorQueryDto) {

        PageHelper.startPage(poorQueryDto.getPageNum(), poorQueryDto.getPageSize());
        List<PoorVo> poorVos = dsmsPoorMapper.queryListWithPage(poorQueryDto);

        if (!CollectionUtils.isEmpty(poorVos)) {
            for (PoorVo poorVo : poorVos) {
                DsmsUnit townUnit = dsmsUnitService.selectByKey(poorVo.getTown());
                DsmsUnit villageUnit = dsmsUnitService.selectByKey(poorVo.getVillage());

                if (townUnit != null) {
                    poorVo.setTownStr(townUnit.getName());
                }

                if (villageUnit != null) {
                    poorVo.setVillageStr(villageUnit.getName());
                }
            }
        }

        return poorVos;
    }

    /**
     * 新增特困人员
     *
     * @param poorDto the poor dto
     * @param login   the login user
     * @return the int.
     */
    @Override
    public Integer save(PoorDto poorDto, DsmsUser login) {

        DsmsPoor dsmsPoor = new DsmsPoor();
        BeanUtils.copyProperties(poorDto, dsmsPoor);
        dsmsPoor.setUpdateInfo(login);
        dsmsPoor.setStatus(PoorStatusEnum.ENABLE.getType());

        // 判断单位是否存在
        DsmsUnit dsmsUnit = dsmsUnitService.selectByKey(poorDto.getUnitId());
        if (PublicUtil.isEmpty(dsmsUnit)) {
            throw new BusinessException(ErrorCodeEnum.GB10031001);
        }
        dsmsPoor.setUnitName(dsmsUnit.getName());

        // 判断身份证是否重复
        if (!checkIdCard(null, poorDto.getIdCard())) {
            throw new BusinessException(ErrorCodeEnum.GB10051002, poorDto.getIdCard());
        }

        if (!IDCardUtil.isIDNumber(poorDto.getIdCard())) {
            throw new BusinessException(ErrorCodeEnum.GB10051009, poorDto.getIdCard());
        }

        Integer result = dsmsPoorMapper.insertSelective(dsmsPoor);
        if (result > 0 && PublicUtil.isNotEmpty(poorDto.getProjectIdList())) {
            List<DsmsPoorProject> poorProjectList = Lists.newArrayList();
            for (Long projectId : poorDto.getProjectIdList()) {
                DsmsPoorProject poorProject = new DsmsPoorProject();
                poorProject.setPoorId(dsmsPoor.getId());
                poorProject.setProjectId(projectId);
                poorProjectList.add(poorProject);
            }
            dsmsPoorProjectService.batchSave(poorProjectList);
        }

        return result;
    }

    /**
     * 校验身份证号码是否存在
     *
     * @param id     the poor id
     * @param idCard the id card
     * @return true-不存在 false-存在
     */
    public boolean checkIdCard(Long id, String idCard) {

        Preconditions.checkArgument(PublicUtil.isNotEmpty(idCard),
                csunMessageSource.getMessage("id.card.null", null));

        Example example = new Example(DsmsPoor.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("idCard", idCard);
        if (id != null) {
            criteria.andNotEqualTo("id", id);
        }

        int result = selectCountByExample(example);

        return result < 1;
    }

    /**
     * 修改特困人员信息
     *
     * @param poorDto the poor dto
     * @param login   the login user
     * @return the int.
     */
    @Override
    public Integer edit(PoorDto poorDto, DsmsUser login) {

        DsmsPoor dsmsPoorQuery = dsmsPoorMapper.selectByPrimaryKey(poorDto.getId());
        if (PublicUtil.isEmpty(dsmsPoorQuery)) {
            throw new BusinessException(ErrorCodeEnum.GB10041001);
        }

        DsmsPoor dsmsPoor = new DsmsPoor();
        BeanUtils.copyProperties(poorDto, dsmsPoor);
        dsmsPoor.setUpdateInfo(login);

        if (PublicUtil.isNotEmpty(poorDto.getUnitId())) {
            // 判断单位是否存在
            DsmsUnit dsmsUnit = dsmsUnitService.selectByKey(poorDto.getUnitId());
            if (PublicUtil.isEmpty(dsmsUnit)) {
                throw new BusinessException(ErrorCodeEnum.GB10031001);
            }
            dsmsPoor.setUnitName(dsmsUnit.getName());
        }

        if (PublicUtil.isNotEmpty(poorDto.getIdCard())) {
            // 判断身份证是否重复
            if (!checkIdCard(poorDto.getId(), poorDto.getIdCard())) {
                throw new BusinessException(ErrorCodeEnum.GB10051002);
            }
        }

        Integer result = dsmsPoorMapper.updateByPrimaryKeySelective(dsmsPoor);

        if (PublicUtil.isNotEmpty(poorDto.getProjectIdList())) {
            DsmsPoorProject poorProjectDelete = new DsmsPoorProject();
            poorProjectDelete.setPoorId(dsmsPoor.getId());
            dsmsPoorProjectService.delete(poorProjectDelete);
            List<DsmsPoorProject> poorProjectList = Lists.newArrayList();
            for (Long projectId : poorDto.getProjectIdList()) {
                DsmsPoorProject poorProject = new DsmsPoorProject();
                poorProject.setPoorId(dsmsPoor.getId());
                poorProject.setProjectId(projectId);
                poorProjectList.add(poorProject);
            }
            dsmsPoorProjectService.batchSave(poorProjectList);
        }

        return result;
    }

    /**
     * 通过Id查询特困人员信息.
     *
     * @param poorId the poor id
     * @return the poor vo.
     */
    @Override
    public PoorVo showById(Long poorId) {

        return dsmsPoorMapper.showById(poorId);
    }

    /**
     * 通过Id删除特困人员信息.
     *
     * @param poorId the poor id
     * @return the int.
     */
    @Override
    public Integer deleteById(Long poorId) {

        DsmsPoorProject poorProjectDelete = new DsmsPoorProject();
        poorProjectDelete.setPoorId(poorId);
        dsmsPoorProjectService.delete(poorProjectDelete);

        // 删除任务
        DsmsRecord dsmsRecord = new DsmsRecord();
        dsmsRecord.setPoorId(poorId);
        dsmsRecord.setStatus(1);
        dsmsRecordService.delete(dsmsRecord);

        return dsmsPoorMapper.deleteByPrimaryKey(poorId);
    }

    /**
     * 根据Id修改特困人员信息.
     *
     * @param dsmsPoor the dsms poor
     * @param login    the login user
     * @return the int.
     */
    @Override
    public Integer modifyPoorStatusById(DsmsPoor dsmsPoor, DsmsUser login) {

        DsmsPoor dsmsPoorQuery = dsmsPoorMapper.selectByPrimaryKey(dsmsPoor.getId());
        if (PublicUtil.isEmpty(dsmsPoorQuery)) {
            throw new BusinessException(ErrorCodeEnum.GB10041001);
        }

        return dsmsPoorMapper.updateByPrimaryKeySelective(dsmsPoor);
    }

    /**
     * 审核特困人员
     *
     * @param applyPoorDto the apply poor dto
     * @param login        the login user
     * @return the int.
     */
    @Override
    @Transactional
    public Integer apply(ApplyPoorDto applyPoorDto, DsmsUser login) {
        List<Long> poorIds = applyPoorDto.getPoorIds();
        int i = 0;
        if (!CollectionUtils.isEmpty(poorIds)) {
            for (Long poorId : poorIds) {
                DsmsPoor dsmsPoorQuery = dsmsPoorMapper.selectByPrimaryKey(poorId);
                if (PublicUtil.isEmpty(dsmsPoorQuery)) {
                    throw new BusinessException(ErrorCodeEnum.GB10041001);
                }

                if (dsmsPoorQuery.getApply() > 0) {
                    throw new BusinessException(ErrorCodeEnum.GB10041002);
                }

                if (applyPoorDto.getApply().equals(2)) {
                    if (PublicUtil.isEmpty(applyPoorDto.getReason())) {
                        throw new BusinessException(ErrorCodeEnum.GB10041003);
                    }
                }

                DsmsPoor dsmsPoor = new DsmsPoor();
                dsmsPoor.setId(poorId);
                dsmsPoor.setApply(applyPoorDto.getApply());
                dsmsPoor.setReason(applyPoorDto.getReason());
                dsmsPoor.setUpdateInfo(login);
                i += dsmsPoorMapper.updateByPrimaryKeySelective(dsmsPoor);
            }
        }
        return i;
    }

    /**
     * 查询特困人员定位信息
     *
     * @param unitIdList the unit id list
     * @return the poor vo
     */
    @Override
    public List<PoorVo> queryPoorLocationList(List<Long> unitIdList) {

        return dsmsPoorMapper.queryPoorLocationList(unitIdList);
    }

    /**
     * 查询特困人员服务详情
     *
     * @param id the poor id
     * @return the poor vo
     */
    @Override
    public PoorVo showPoorDetailById(Long id) {

        PoorVo poorVo = showById(id);
        if (PublicUtil.isEmpty(poorVo)) {
            throw new BusinessException(ErrorCodeEnum.GB10041001);
        }

        List<ProjectPercentVo> projectPercentVoList = dsmsRecordService.queryProjectPercent(id, DateUtil.getNowMonth());

        for (PoorProjectVo ppv : poorVo.getProjectVoList()) {
            for (ProjectPercentVo item : projectPercentVoList) {
                if (ppv.getProjectId().equals(item.getProjectId())) {
                    ppv.setTotal(item.getTotal());
                    ppv.setFinish(item.getFinish());
                }
            }
        }

        return poorVo;
    }

    /**
     * 获取每年每个地方的特困人员数量
     *
     * @param year 年-yyyy
     * @return the poor number vo list.
     */
    @Override
    public List<PoorNumberVo> queryPoorNumberList(String year) {
        //查询镇pid
        Integer select = dsmsUnitService.selectUnitByPid();

        return dsmsPoorMapper.queryPoorNumberList(year,select);
    }

    /**
     * 查询总数
     *
     * @param year 年-yyyy
     * @return the poor total number.
     */
    @Override
    public Integer queryPoorTotal(String year) {

        return dsmsPoorMapper.queryPoorTotal(year);
    }

    /**
     * 根据单位id查询特困人员id
     *
     * @param unitIdList the unit id list.
     * @return the poor id list.
     */
    @Override
    public List<Long> selectPoorIdListByUnitList(List<Long> unitIdList) {

        return dsmsPoorMapper.selectPoorIdListByUnitList(unitIdList);
    }

    // 根据片区id查询所有的特困人员
    @Override
    public List<PoorVo> selectPoorByUnitList(List<Long> unitIdList) {
        return dsmsPoorMapper.selectPoorByUnitList(unitIdList);
    }

    @Override
    public void update(List<String> idCards) {
        dsmsPoorMapper.update(idCards);
    }
    // 根据片区id查询所有的特困人员
    @Override
    public List<Long> selectALLPoorIdListByUnitList(List<Long> unitIdList) {
        return dsmsPoorMapper.selectALLPoorIdListByUnitList(unitIdList);
    }

    @Override
    public void update1(List<String> idCards) {
        dsmsPoorMapper.update1(idCards);
    }

    // 获取特困人员数量村
    @Override
    public List<PoorNumberVo> queryPoorNumberListByVillage(String year) {
        return dsmsPoorMapper.queryPoorNumberListByVillage(year);
    }


}
